<?php

class folio_comment {

    public $ident = -1;
    public $object_id = -1;
    public $object_type = '';
    public $owner = -1;
    public $postedname = '';
    public $body = '';
    public $posted = -1;

    /**
     * Create from a db row
     *
     * @param array $array MySQL array
     * @return folio_comment
     */
    function folio_comment( $array ) {
        // Assume constructor is an array from the db.

        if ( !!$array ) {
            foreach ( $array as $n=>$v ) {
                $this->$n = $v; //( $r . ' = ' . $v . '<br/>' );
            }
        }

    }


    /**
     * Called to delete the artifact from the db.
     *
     * @param folio_comment $comment Comment to delete
     */
    function Delete( folio_comment $comment ) {
        return delete_records( 'comments', 'ident', $comment->ident );
    }

    /**
     * Load a particular comment
     *
     * @param int $ident
     */
    function SelectWhereIdent( $ident ) {
        global $CFG;

        $ident = intval( $ident );

        $query = "SELECT c.ident, c.* FROM {$CFG->prefix}" .
                    "comments c WHERE ident = " . $ident;

        $a = recordset_to_array( get_recordset_sql( $query ));

        if( $a == false ) {
            return false;
        } else {
            return new folio_comment( $a[$ident] );
        }

    }

    /**
     * Load all comments matching the passed page.
     *
     * @param folio_page $page
     * @return array Array of comments.
     */
    function SelectWherePage( $page ) {
        global $CFG;

        $query = "SELECT c.ident, c.* FROM {$CFG->prefix}" .
                    "comments c WHERE c.object_id = " . $page->page_ident .
                    " AND c.object_type='page'";

        $records = recordset_to_array( get_recordset_sql( $query ));
        $comments = array();

        if( $records != false AND count($records) > 0 ) {
            foreach( $records as $c ) {
                $comments[] = new folio_comment( $c );
            }
            return $comments;
        } else {
            return false;
        }
    }

    /**
     * Insert a new comment into the db.
     *
     * @param folio_page $page Page to attach the comment onto
     */
    public function Insert( folio_page $page, $body ) {

        if( !isloggedin() )
            trigger_error('You must be logged in to insert a comment');

        $user = folio_user::SelectWhereIdent( $_SESSION['userid']);

        $i = new StdClass();
        $i->object_id = $page->page_ident;
        $i->object_type = 'page';
        $i->owner = $user->ident;
        $i->postedname = $user->name;
        $i->body = $body;
        $i->posted = time();
        $i = insert_record( 'comments', $i );

        // Load the new decoration from the db for the constructor.
        $c =  folio_comment::SelectWhereIdent( $i );

        plugin_hook("folio_comment","inserted", $c);
        
        return $c;
    }
}

?>
